#include "createchat.h"
#include "authorization.h"
#include "client.h"

createChat::createChat(QWidget* parent) :
    QDialog(parent)
{
    this->setFixedSize(300, 150);
    checking = false;
    build();
    connecting();
}

void createChat::build()
{
    titleEdit = new QLineEdit;
    nameParticipantEdit = new QLineEdit;
    formLayout = new QFormLayout;

    formLayout->addRow(tr("Title: "), titleEdit);
    formLayout->addRow(tr("Name of the participant: "), nameParticipantEdit);

    buttonsLayout = new QHBoxLayout;
    okButton = new QPushButton(tr("Ok"));
    cancelButton = new QPushButton(tr("Cancel"));
    buttonsLayout->addWidget(cancelButton);
    buttonsLayout->addWidget(okButton);

    infoLabel = new QLabel;

    commonVLayout = new QVBoxLayout;
    commonVLayout->addLayout(formLayout);
    commonVLayout->addWidget(infoLabel);
    commonVLayout->addLayout(buttonsLayout);

    setLayout(commonVLayout);
}

void createChat::connecting()
{
    connect(okButton, &QPushButton::clicked, this, &createChat::createChatOkAction);
    connect(cancelButton, &QPushButton::clicked, this, [&]()
    {
        close();
    });
}

void createChat::createChatOkAction()
{
    char buffer[BUFFER_SIZE];
    QString sqlQuery;
    std::string sqlQueryStd;
    int count = 0;
    QSqlQuery query;
    QString title = titleEdit->text();
    QString nameParticipant = nameParticipantEdit->text();

    sqlQuery = QString("SELECT COUNT(*) FROM listChat WHERE nickName = '%1' AND chat = '%2'").arg(clientStartNickname()).arg(title);
    sqlQueryStd = sqlQuery.toStdString();
    send(clientSock, sqlQueryStd.c_str(), sqlQueryStd.length(), 0);
    recv(clientSock, buffer, sizeof(buffer), 0);

    if(atoi(buffer) < 1)
    {
        ++count;
    }
    else
    {
        infoLabel->setText(tr("Such a chat name already exists"));
    }

    bool check = false;

    if(title.size() > 20 || title == "" || title.size() < 2)
    {
        check = true;
    }
    else
    {
        ++count;
    }

    int spaceCount = 0;

    for(QChar ch : title)
    {
        if(ch.isLetterOrNumber() || ch == ' ')
        {
            if(ch == ' ')
            {
                ++spaceCount;
            }

            if(spaceCount > 4)
            {
                check = true;
            }
        }
    }

    if(check)
    {
        infoLabel->setText(tr("The name must not be less than 2 characters and not exceed 20, \n"
                     " only letters, numbers and no more than 4 spaces are allowed."));
    }
    else
    {
        ++count;
    }

    sqlQuery = QString("SELECT COUNT(*) FROM Authorization WHERE nickName = '%1'").arg(nameParticipant);
    sqlQueryStd = sqlQuery.toStdString();
    send(clientSock, sqlQueryStd.c_str(), sqlQueryStd.length(), 0);
    recv(clientSock, buffer, sizeof(buffer), 0);

    if(atoi(buffer) > 0)
    {
        ++count;
    }
    else
    {
        infoLabel->setText(tr("A user with this nickname has not been found"));
    }

    if(nameParticipant != clientStartNickname())
    {
        ++count;
    }
    else
    {
        infoLabel->setText("It is impossible to create a chat with yourself");
    }

    if(count == 5)
    {
        checking = true;
    }

    if(checking)
    {
        sqlQuery = QString("INSERT INTO listChat(nickName, chat) VALUES('%1', '%2')").arg(clientStartNickname()).arg(title);
        sqlQueryStd = sqlQuery.toStdString();
        send(clientSock, sqlQueryStd.c_str(), sqlQueryStd.length(), 0);

        sqlQuery = QString("INSERT INTO listChat(nickName, chat) VALUES('%1', '%2')").arg(nameParticipant).arg(title);
        sqlQueryStd = sqlQuery.toStdString();
        send(clientSock, sqlQueryStd.c_str(), sqlQueryStd.length(), 0);

        std::this_thread::sleep_for(std::chrono::nanoseconds(150000000));

         QString renderingEveryone = QString("update_chat_list:'%1'").arg(nameParticipant);
         std::string renderingEveryoneStr = renderingEveryone.toStdString();
         send(clientSock, renderingEveryoneStr.c_str(), renderingEveryoneStr.length(), 0);

        std::this_thread::sleep_for(std::chrono::nanoseconds(150000000));
        emit accepted();
        this->close();
    }
}

